if(!caryr){
	caryr = {};
}
if(!caryr.cuz){
	caryr.cuz = {};
}
caryr.cuz.layout = {
	layoutObjName:'',	
	objFields:null,
	layoutModal:null,	
	layoutList:null,
	currentLayout:null,
	layoutType:'',
	tree:null,
	dataTable:null,
	applyLayout:null,
	
	init:function(option){				/******** Method: Initialization *****/
		this.layoutModal = option.layoutModal;
		this.tree = this.layoutModal.find('#layoutTree');//option.tree;
		this.layoutObjName = option.layoutObjName;
		this.objFields = option.objFields;
		this.dataTable = option.dataTable;
		
		that = this;
		this.fetchLayout(this);	 		/* Get Layout List */
		//this.createTree(option.createTreeCallBack);
		this.createTree(function(){
			that.layoutModal.modal('show');
			that.toggleLayoutEdit(false);
		});

		$('#btn-layout-add').on('click',function(){	 		/* Attach Event: add button */
			var options = that.layoutModal.find('#fg-layout-name-list select option');
			if(options&&options.length == 10){
				that.layoutModal.modal('hide');
				swal({
					title:$.i18n.prop("msg_layout_max_layouts"),
					text: "",
					type: "error"
					},function(){
						that.layoutModal.modal('show');
					}
				);
			}else{
				that.toggleLayoutEdit(true);
				that.currentLayout = {};
				that.refreshModalData();
			}
	 	});
		
		$('#btn-layout-edit').on('click',function(){	 	/* Attach Event: add button */
 			var id = that.layoutModal.find('#fg-layout-name-list select').val();
 			if(!id){
 				swal({title:msgTxt,text: "",type: "info"});
 				return;
 			}
 			that.toggleLayoutEdit(true);
 			that.currentLayout = that.findLayoutById(id);
	 	});
		
		$('#btn-layout-cancel').on('click',function(){	 	/* Attach Event: cancel button */
 			that.toggleLayoutEdit(false);
 			if(that.layoutList[0]){
 				that.currentLayout = that.layoutList[0];
 			}else{
 				that.currentLayout = {};
 			}
 			that.refreshModalData();
	 	});
		
		$('#btn-layout-del').on('click',function(){		 	/* Attach Event: delete button */ 
			that.currentLayout = {};
			var id = that.layoutModal.find('#fg-layout-name-list select').val();
			if(!id){
				var msgTxt = $.i18n.prop("msg_com_systemError");
				return;
			}
			var ids = new Array();
				ids.push(id);
			var option ={
				confirmMsg  :  $.i18n.prop("msg_com_confirmDel"),
				url: "../erp/delete-"+that.layoutObjName,
				callback:function(){
					that.fetchLayout(that);
					that.toggleLayoutEdit(false);
				},
				data: {  
					ids:ids
	          	},
			}
			that.postReqLayout(option);
		});
		$('#btn-layout-save').on('click',function(){		/* Attach Event: save button */
			var name = that.layoutModal.find('#fg-layout-name input').val();
			var treeData = that.collectTreeData();
			
			if(treeData==''){
				that.layoutModal.modal('hide');
				swal({
					title:$.i18n.prop("msg_layout_pls_selectFields"),
					text: "",
					type: "error"
					},function(){
						that.layoutModal.modal('show');
					}
				);
				return;
			}
			if(name==''){
				that.layoutModal.modal('hide');
				swal({
					title:$.i18n.prop("msg_layout_pls_inputName"),
					text: "",
					type: "error"
					},function(){
						that.layoutModal.modal('show');
					}
				);
				return;
			}
			
			var option ={
				confirmMsg  :  $.i18n.prop("msg_com_confirmSave"),
				url: "../erp/update-"+that.layoutObjName,
				callback:function(){
					that.fetchLayout(that);
					that.toggleLayoutEdit(false);
				},
				data: {  
					id: 	that.currentLayout.id,
					comp: 	that.currentLayout.comp,
					userId:	that.currentLayout.userId,
					name: name,
					objectName: that.layoutObjName,
					layoutType: that.layoutType,
				    layout :treeData
	          	},
			}
			that.postReqLayout(option);
	 	});
		
		this.layoutModal.find('#fg-layout-name-list select').on('change',function(e){	/* Attach Event: select change */
			var layoutId = $(this).val();
			that.currentLayout = that.findLayoutById(layoutId);
			that.refreshModalData();
		})
		
		if(option.applyLayout){					/* Attach Event: apply change */											
			var tableId = option.tableId;
			this.applyLayout = option.applyLayout;
			$('#btn-layout-apply').on('click',function(){
				var fields = that.currentLayout.layout.split(',');
				that.dataTable = option.applyLayout(fields);
			});
		}
	},
	refreshModalData: function(){		/******** Method: refreshModalData *****/
		this.layoutModal.find('#fg-layout-name input').val(this.currentLayout.name);
		var layoutStr = this.currentLayout.layout;
		var fields = [];
		if(layoutStr){
			fields = layoutStr.split(',');
		}
		this.updateTreeData(this.tree, fields);
	},
	createTree: function(callback) {
		var trData = this.getLayoutTreeData(this.objFields);
		this.tree.bind('ready.jstree', function(e, data) { 
			if(callback){
				callback();
			}
		});
		this.tree.jstree({
            "core" : {
                "themes" : {
                    "responsive": false
                }, 
                "check_callback" : true,
                'data': trData
            },
            "types" : {
                "default" : {
                	"valid_children" : [],
                    "icon" : "fa fa-sort-numeric-asc icon-state-success icon-lg"
                }
            },
            "state" : { "key" : "demo2" },
            "plugins" : [ "dnd", "state","checkbox", "types" ]
        });
		return this.tree;
    },
    fetchLayout: function(cusLayout){
    	var cuzLayout = cusLayout;
    	var select = $('#fg-layout-name-list').find('select');
    	var url = '../erp/json-'+cusLayout.layoutObjName+'-list'; 

    	caryr.fetchRefListNew({
       		refSelect:select ,
			url:url,
			orderBy:'updatedAt desc',
			callback:function(data){
				select.find('option').remove();
				cuzLayout.layoutList = data;
				for(var i=0;i<data.length;i++){
					var html = '<option value="'+data[i].id+'">'+data[i].name+'</option>'
					select.append(html);
				}
				
				if(data[0]){
					cuzLayout.currentLayout = data[0];
					/*"Apply layout after fectch
					var fields = that.currentLayout.layout.split(',');
					cuzLayout.dataTable = cuzLayout.applyLayout(fields);*/
				}else{
					cuzLayout.currentLayout = {};
				}
				cuzLayout.refreshModalData();
			}
        });
    },
    toggleLayoutEdit: function(editMode){
 		if(editMode){
 			$('#fg-layout-name-list').addClass('hidden');
	 		$('#fg-layout-name').removeClass('hidden');
	 		$('#btn-layout-add').addClass('hidden');
	 		$('#btn-layout-edit').addClass('hidden');
	 		$('#btn-layout-cancel').removeClass('hidden');
	 		$('#btn-layout-save').removeClass('hidden');
	 		$('#btn-layout-modal-close').addClass('hidden');
	 		$('#btn-layout-apply').addClass('hidden');
	 		
	 		this.toggleTree(this.tree,true);
 		}else{
 			$('#fg-layout-name-list').removeClass('hidden');
	 		$('#fg-layout-name').addClass('hidden');
	 		$('#btn-layout-add').removeClass('hidden');
	 		$('#btn-layout-edit').removeClass('hidden');
	 		$('#btn-layout-cancel').addClass('hidden');
	 		$('#btn-layout-save').addClass('hidden');
	 		$('#btn-layout-modal-close').removeClass('hidden');
	 		$('#btn-layout-apply').removeClass('hidden');
	 		
	 		this.toggleTree(this.tree,false);
 		}
 	},
 	getLayoutTreeData: function(objFieldList){
 		var data = [];
 		for(var i =0;i<objFieldList.length;i++){
 			var text = $.i18n.prop('msg_'+this.layoutObjName+'_field_'+objFieldList[i]);;
 			data[i]= {
                  "text" : text,
                  "id"   : objFieldList[i],
                  "state": { "selected": false }
           };
 		}
 		return data;
	},
	postReqLayout: function(option){
		var layoutModel = this.layoutModal;
		layoutModel.modal('hide');
		swal({
			  title: option.confirmMsg,
			  text: "",
			  type: "info",
			  showCancelButton: true,
			  closeOnConfirm: false,
			  showLoaderOnConfirm: true
			}, function (isConfirm){
				if(isConfirm){
					$.ajax({
						type:"post",  
			   			url: option.url,  
			   			traditional:true,
			   			data: option.data,
			          	success:function(data){
			          		var msgTxt = caryr.serverMsg(data);
			          		swal({title:msgTxt,text: "",type: "success"});
			          		if(option.callback){
			          			option.callback();
			          		}
			    		}, 
			    		error: function(XMLHttpRequest, textStatus, errorThrown) {
							var msgTxt = $.i18n.prop("msg_com_systemError");
							swal({title:msgTxt,text: "",type: "error"});
		                } 
					});
				}else{
					layoutModel.modal('show');
				}
		});
	},
	collectTreeData: function(){
		var layoutFields = '';
		var selectedNodes = this.tree.jstree("get_selected");
		var treeJson      = this.tree.jstree("get_json");
		
		for(var i =0;i<treeJson.length;i++){
			var id = treeJson[i].id;
			for(var j =0;j<selectedNodes.length;j++){
				if(id == selectedNodes[j] ){
					layoutFields += id + ',';
				}
			}
		}
		if(layoutFields!=''){
			layoutFields = layoutFields.substr(0,layoutFields.length-1);
		}
		/*if(selectedNodes){	// Issue: the nodes is not sorted.
			layoutFields = ''+selectedNodes;
		}*/
		return layoutFields;
	},
	updateTreeData: function (tree,fields){
		tree.jstree("uncheck_all");
		var selectedNodeIds = {};
	 	for(var i = fields.length-1;i>=0;i--){
			tree.jstree("check_node", $('#' + fields[i]));
			tree.jstree("move_node", $('#' + fields[i]),tree,'first');
		}
	},
	toggleTree :function (tree,editable){
		if(editable){
			$(tree.jstree().get_json(tree, { flat: true})).each(function(index, value) {
			      tree.jstree().enable_node(this.id);
			});
		}else{
			$(tree.jstree().get_json(tree, { flat: true})).each(function(index, value) {
			      tree.jstree().disable_node(this.id);
			});
		}
	},
	findLayoutById: function(id){
		var layout = {}
		for(var i =0;i<that.layoutList.length;i++){
			if(id == that.layoutList[i].id){
				layout = that.layoutList[i];
				break;
			}
		}
		return layout;
	}
}
